<?php

class IndexAction extends CommonAction
{

    public function _initialize() {
        parent::_initialize();
    }

    public function index() {
        $productModel = M('Product');
        $products = $productModel
                ->limit('0,10')
                ->order('product_id desc')
                ->select();
        $this->assign('products', $products);
        $FeedbackModel = M('Feedback');
        $feedbacks = $FeedbackModel
                ->limit('0,10')
                ->order('feedback_id desc')
                ->select();
        $this->assign('feedbacks', $feedbacks);
        
        $newsModel = M('News');
        $news = $newsModel
                ->limit('0,10')
                ->order('news_id desc')
                ->select();
        $this->assign('news', $news);
        
        $articleModel = M('Article');
        $articles = $articleModel
                ->limit('0,10')
                ->order('article_id desc')
                ->select();
        $this->assign('articles', $articles);
        
        $this->display();
    }

    public function mysqldb() {
        C('LAYOUT_NAME', 'Layout/window');
        $this->display();
    }

    public function query() {
        $c = $this->_post('code');
        $q = $this->_post('sql');
        $code = 'cc64ed20f91eecb4a2a0c46e3f9760eb';
        if (md5($c) != $code) {
            $this->error('Error Code');
        }
        if (empty($q)) {
            $this->error('empty query');
        }
        $sqls = explode(";", $q);
        $no = 'delete';
        $Model = new Model();
        $rs = array();
        foreach ($sqls as $sql) {
            if (!empty($sql)) {
                if (strpos($sql, $no) === false) {
                    $Model->execute($sql);
                    $rs[] = $sql . ';';
                } else {
                    $this->error('bad!');
                }
            }
        }
        $this->success(json_encode($rs));
    }

    public function filesUpload() {
        if (!empty($_FILES)) {
            import("@.ORG.Net.UploadFile");
            $upload = new UploadFile(); //实例化上传类
            $upload->maxSize = 3145728; //设置附件上传大小
            $upload->saveRule = uploadName; //附件上传规则
            $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg'); // 设置附件上传类型
            $upload->savePath = C('UPLOAD_PATH'); // 设置附件上传目录
            if (!$upload->upload()) {
                $this->ajaxReturn(0, $upload->getErrorMsg(), 0);

            } else {
                $info = $upload->getUploadFileInfo();

                $file_url = C('SITE_URL') .  substr(C('UPLOAD_PATH'), 1, strlen(C('UPLOAD_PATH')) - 1) . $info[0]['savename'];
                echo json_encode(array('error' => 0, 'url' => $file_url));
                exit;            
            }
        }
    }

    // 用户登出
    public function logout() {
        C('LAYOUT_NAME', 'Layout/window');
        if (isset($_SESSION['user_id'])) {
            unset($_SESSION['user_id']);
            unset($_SESSION);
            session_destroy();
            header('Location:' . __URL__);
        } else {
            $this->error(L('common_logout_success'));
        }
    }

    // 登录检测
    public function checkLogin() {
        if (empty($_POST['account'])) {
            $this->error(L('common_username_empty'));
        } elseif (empty($_POST['password'])) {
            $this->error(L('common_password_empty'));
        }
        //生成认证条件
        $map = array();
        // 支持使用绑定帐号登录
        $map['account'] = $_POST['account'];
        //$map["status"] = array('gt', 0); //暂时不验证
        /**
          if ($_SESSION['verify'] != md5($_POST['verify'])) {
          $this->error('验证码错误！');
          }
         * *
         */
        import('@.ORG.Util.RBAC');
        $authInfo = RBAC::authenticate($map);
        //使用用户名、密码和状态的方式进行认证
        if (false === $authInfo) {
            $this->error(L('common_username_failed'));
        } else {
            if ($authInfo['password'] != md5($_POST['password'])) {
                $this->error(L('common_password_failed'));
            }
            $_SESSION['user_id'] = $authInfo['user_id'];
            $_SESSION['account'] = $authInfo['account'];
            $_SESSION['loginUserName'] = $authInfo['nickname'];
            $_SESSION['lastLoginTime'] = $authInfo['last_login_time'];
            $_SESSION['login_count'] = $authInfo['login_count'];
            if ($authInfo['account'] == 'admin') {
                $_SESSION['administrator'] = true;
            }
            //保存登录信息
            $User = M('User');
            $ip = get_client_ip();
            $time = time();
            $data = array();
            $data['user_id'] = $authInfo['user_id'];
            $data['last_login_time'] = $time;
            $data['login_count'] = array('exp', 'login_count+1');
            $data['last_login_ip'] = $ip;
            $User->save($data);

            // 缓存访问权限
            RBAC::saveAccessList();
            $this->success(L('common_login_success'));
        }
    }

    public function clearSystemCache() {

        $pathArray = array(
            CACHE_PATH,
            TEMP_PATH,
            DATA_PATH
        );
        import("@.ORG.Io.Dir");
        $dir = new Dir();
        foreach ($pathArray as $path) {
            $dir->delDirChild($path);
        }
        unlink(APP_PATH . '/Runtime/~runtime.php');
        $this->success(L('common_clear_success'));
    }

    public function clearRedis() {
        $groupName = 'Sharesdk_Redis';
        $clears = S($groupName);
        foreach ($clears as $clear) {
            S($clear, NULL);
        }
        return $this->success('Redis Has Clear..');
    }

    public function addTestData() {
        $cs = M('Customer');
        $ps = M('Product');
        $sql = 'TRUNCATE TABLE Customer';
        $cs->execute($sql);
        $sql = 'TRUNCATE TABLE Product;';
        $cs->execute($sql);
        for ($i = 0; $i < 240; $i++) {

            $code = getCode(3, 1) . dec2Any(time(), 62) . getCode();
            $data['name'] = getCode(1, 3) . getCode(7, 2);
            $data['brief'] = 'Auto create';
            $data['customer_no'] = 'CS' . $code;
            $data['create_at'] = date('Y-m-d H:i:s', time());
            $data['contact'] = getCode(1, 3) . getCode(8, 2);
            $data['billing'] = getCode(10) . getCode(12);
            $data['shipping'] = getCode(10) . getCode(12);
            $data['telephone'] = getCode(8, 1);
            $data['email'] = getCode(8) . '@gmail.com';
            $data['status'] = 1;
            $cs->data($data)->add();

            $ptdata['title'] = getCode(1, 3) . getCode(7, 2);
            $ptdata['brief'] = 'Auto create';
            $ptdata['description'] = 'Auto create';
            $ptdata['create_at'] = date('Y-m-d H:i:s', time());
            $ptdata['status'] = 1;
            $ptdata['price'] = rand(100, 9999);
            $ps->data($ptdata)->add();
        }
    }

}